<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Assessment;
use App\Models\Category;
use App\Models\Child;
use App\Models\ChildStar;
use App\Models\Device;
use App\Models\DeviceGrade;
use App\Models\Game;
use App\Models\Grade;
use App\Models\History;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Log;

class ChildController extends BaseController
{
    /*孩子列表*/
    public function index(Request $request){
        $user = $this->getUser();
        $page_num = config("site.other.paginate");
        $paginate = $request->input("paginate");

        if (isset($paginate) && is_numeric($paginate) && $paginate > 0){
            $page_num = $paginate;
        }
        $start = 0;
        $page = $request->input("page");
        if (isset($page) && is_numeric($page) && $page > 0){
            $start = ($page - 1) * $page_num;
        }
        $children = $user->children()
            ->offset($start)
            ->limit($page_num)
            ->orderBy("current", "desc")
            ->orderBy("last_use_time", "desc")
            ->orderBy("id", "desc")
            ->get();

        $grades = Grade::getArr();
        $catgories = Category::getArr();

        $children->each(function (&$item) use ($grades, $catgories){
            $item->history = $this->getHistory($item->id, $grades, $catgories);
        });

        $page_count = floor($user->children()->count() / $page_num);
        $children = $children->toArray();

        return $this->json(compact( 'children', 'page_count'));
    }

    public function add(Request $request)
    {


        $this->validate($request, [
            'name' => 'required|max:255',
            'birthday' => 'required|date',
            'sex' => 'required|in:0,1',
        ], [], [
            'name' => __("Username"),
            'birthday' => __("Birthday"),
            'sex' => __("Sex"),
        ]);

        $user = $this->getUser();

        $data = $request->only(['name', 'birthday', 'sex']);
        $data['user_id'] = $user->id;
        $data['agency_id'] = $user->agency_id;

        if (Child::create($data)) {
            return $this->json([]);
        }

        return $this->json([], config("apicode.serverError.msg"), config("apicode.serverError.code"));

    }

    //todo:后期添加,2020-08-17
    public function edit($id, Request $request)
    {
        $child = Child::find($id);
        if (empty($child)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }

        if ($request->isMethod("post")) {
            $this->validate($request, [
                'name' => 'required|max:255',
                'birthday' => 'required|date',
                'sex' => 'required|in:0,1',
                'address' => 'required|max:255',
                'phone' => 'required|string|max:11',
            ], [], [
                'name' => __("Username"),
                'birthday' => __("Birthday"),
                'sex' => __("Sex"),
                'address' => 'required|max:255',
                'phone' => 'required|string|max:11',
            ]);
            $data = $request->only(['name', 'birthday', 'sex', 'address', 'phone']);

            if ($child->update($data)) {
                return redirect()->route('admin.child.index', ['user_id' => $child->user_id])->with('success', __('Edit success'));
            }

            return back()->with('error', __('Edit failed'));
        } else {

            return backendView('child.edit', compact('child'));
        }
    }

    //todo:后期添加2020-08-17
    public function delete($id)
    {
        $child = Child::find($id);

        if (empty($child)) {
            return back()->with('error', __('The page you requested was not found'))->withInput();
        }
        $user = $this->getUser();
        if (!$user->can('allow', $child)) {
            return back()->with('error', __("Sorry, you are not authorized to access this page."));
        }
/*
        $assessment = Assessment::where("child_id", $id)->exists();

        if (count($assessment) > 0) {
            return back()->with('error', "学生有评测数据关联，无法删除");
        }
        */
        if ($child->delete()) {
            return back()->with('success', __('Delete success'));
        }

        return back()->with('error', __('Delete failed'));
    }

    public function star(Request $request)
    {

        $this->validate($request, [
            'child_id' => 'required|integer|exists:children,id',
            'category_id' => 'sometimes|exists:categories,id',
            'grade_id' => 'sometimes|exists:grades,id',
            'device_code' => 'required|exists:devices,code'
        ], [], [
            'child_id' => "学生",
            'category_id' => __("category"),
            'grade_id' => __("grade"),
            'device_code' => "设备号"
        ]);

        $child_id = $request->input("child_id");
        $category_id = $request->input("category_id");
        $grade_id = $request->input("grade_id");
        $device_code = $request->input("device_code");
        $device = Device::where(['code'=>$device_code, 'agency_id'=>$this->getUser()->agency_id])->first();
        if (empty($device_code)){
            return $this->json([],  config("apicode.verifyDeviceFail.msg"), config("apicode.verifyDeviceFail.code"));
        }
        $deviceGrades = DeviceGrade::where("device_id", $device->id)->pluck("grade_id")->toArray();

        $result = ChildStar::select('code', 'star', 'last_star')
            ->where("child_id", $child_id)
            ->when($category_id, function ($query) use ($request, $category_id) {
                $query->where("category_id", $category_id);
            })
            ->when($grade_id, function ($query, $grade_id) {
                $query->where("grade_id", $grade_id);
            })->get()->toArray();

        $played = [];
        foreach ($result as $v){
            $played[$v["code"]] = $v;
        }

        $games = Game::when($category_id, function ($query, $category_id) {
                $query->where("category_id", $category_id);
            })
            ->when($grade_id, function ($query, $grade_id) {
                $query->where("grade_id", $grade_id);
            })->get();

        $result = [];

        foreach ($games as &$v){
            if(in_array($v->code, array_keys($played))){
                $tmp = $played[$v->code];
            }else{
                $tmp = collect(['code'=>$v->code, 'star'=>'', 'last_star'=>'']);
            }
            //Log::error('child/star,game grade_id:'.$v->grade_id);
            //Log::error($deviceGrades);
            $tmp['enable'] = in_array($v->grade_id, $deviceGrades) ? 1 : 0;
            $result[] = $tmp;
        }

        return $this->json(['child_star'=>$result]);
    }

    private function getHistory($child_id, $grades=[], $catgories=[]){

        $history = History::where("child_id",$child_id)
            ->select("grade_id", "category_id", "game_id", 'end_star')
            ->orderBy("id", "desc")->first();

        if (!empty($history)) {
            $history->grade = !empty($history->grade_id) ? $grades[$history->grade_id] : 0;
            $history->category = !empty($history->category_id) ? $catgories[$history->category_id] : 0;
            $game = Game::select('code','name')->find($history->game_id);
            $history->game =$game->name;
            $history->game_code =$game->code;
        }else{
            //Log::error("empty");
            $data = ['grade_id'=>1,
                'category_id'=>1,
                'game_id'=>0,
                'end_start'=>0,
                'game'=>'',
                'game_code'=>'',
            ];
            $data['grade'] = $grades[$data["grade_id"]];
            $data['category'] = $catgories[$data["category_id"]];

            $history = collect($data);

            //Log::error($history);
        }

        return $history;
    }
}
